<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章来源" prop="articleOrigin">
        <el-input
          v-model="queryParams.articleOrigin"
          placeholder="请输入文章来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="栏目名称" prop="columnId">
        <el-select v-model="queryParams.columnId" placeholder="请选择栏目名称"
            clearable
            filterable
          >
            <el-option
              v-for="item in columnOptions"
              :key="item.columnId"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="责任编辑" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入责任编辑"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="显示状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择"
                   clearable
                   style="width: 160px;"
        >
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['river_news:river_news:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['river_news:river_news:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['river_news:river_news:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['river_news:river_news:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="river_newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="id" align="center" prop="newsId" /> -->
      <el-table-column label="标题" align="center" prop="title" >
        <template slot-scope="scope">
          {{ $stripHtml(scope.row.title) }}
        </template>
      </el-table-column>
      <el-table-column label="文章来源" align="center" prop="articleOrigin" />
      <el-table-column label="栏目名称" align="center" prop="columnName" />
      <el-table-column label="内容" align="center" prop="content" >
        <template slot-scope="scope">
          <div class="content-cell">{{ $formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>>
      <el-table-column label="责任编辑" align="center" prop="author" />
      <el-table-column label="发布日期" align="center" prop="pubdate" width="180" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 || scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === 0 || scope.row.status === '0' ? '显示' : '隐藏' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封面路径" align="center" prop="coverPath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverPath" width="50" height="50"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="120" class-name="small-padding">
        <template slot-scope="scope">
          <div style="display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 2px;">
            <div style="display: flex; justify-content: center; align-items: center; gap: 2px;">
               <el-button
                size="mini"
                type="text"
                icon="el-icon-arrow-up"
                @click="moveUp(scope.row)"
              >上移</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-arrow-down"
                @click="moveDown(scope.row)"
              >下移</el-button>
            </div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['river_news:river_news:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              :icon="scope.row.status === 0 || scope.row.status === '0' ? 'el-icon-hide' : 'el-icon-view'"
              @click="handleToggleStatus(scope.row)"
              v-hasPermi="['river_news:river_news:edit']"
            >{{ scope.row.status === 0 || scope.row.status === '0' ? '隐藏' : '显示' }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['river_news:river_news:remove']"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改river_news对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <enhanced-editor v-model="form.title" :min-height="120" :max-height="200" placeholder="请输入内容"/>
        </el-form-item>
        <!-- 副标题部分 -->
        <el-form-item label="副标题">
          <div v-for="(subtitle, index) in subtitles" :key="index" class="subtitle-item">
          <enhanced-editor v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`"  :min-height="120" :max-height="200" />
          </div>
          <el-button
            v-if="subtitles.length < 2"
            type="text"
            icon="el-icon-plus"
            @click="addSubtitle"
          >
            添加副标题
          </el-button>
        </el-form-item>
        <el-form-item label="文章来源" prop="articleOrigin">
          <el-input v-model="form.articleOrigin" placeholder="请输入文章来源" />
        </el-form-item>
        <el-form-item label="栏目名称" prop="columnId">
          <el-select
            clearable
            filterable
            v-model="form.columnId" placeholder="请选择">
            <el-option
              placeholder="请选择"
              v-for="item in columnOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="责任编辑" prop="author">
          <el-input v-model="form.author" placeholder="请输入责任编辑" />
        </el-form-item>
        <el-form-item label="发布日期" prop="pubdate">
          <el-date-picker
            v-model="form.pubdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="封面路径" prop="coverPath">
          <el-upload
            ref="upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRiver_news, getRiver_news, delRiver_news, addRiver_news, updateRiver_news,
  addRiver_newsOwn, updateRiver_newsOwn,uploadFile, hideRiverNews, showRiverNews, moveUpRiverNews, moveDownRiverNews} from "@/api/river_news/river_news";
import {getConlumn, listConlumn,listConlumnList} from "@/api/conlumn/conlumn";
import imageCompression from "browser-image-compression";
import EnhancedEditor from "@/components/Editor/EnhancedEditor";

export default {
  name: "River_news",
  dicts: ['status'],
  components: {
    EnhancedEditor
  },
  data() {
    return {
      subtitles: [], // 用于存储副标题的动态数量
      // 上传相关
      fileList: [],
      uploadFile: null,
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // river_news表格数据
      river_newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      columnOptions:[],
      originalFilePath:"",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        articleOrigin: null,
        columnId: null,
        author: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        columnId: [
          { required: true, message: "栏目id不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getColumnList();
    this.getList();
  },

  computed: {
    isFileSelected() {
      return this.form.coverPath instanceof File;
    }
  },
  methods: {

    addSubtitle() {
      if (this.subtitles.length < 2) {
        this.subtitles.push(`littleTitle${this.subtitles.length + 1}`);
      }
    },

    handleFileChange(event) {
      const file = event.target.files[0]; // 获取原生 File 对象
      this.form.coverPath = file;
      console.log(file);
    },

    formatContent(row, column, cellValue, index) {
      const maxLength = 20; // 可根据实际需求调整截取的长度
      if (cellValue && cellValue.length > maxLength) {
        return cellValue.substring(0, maxLength) + '...';
      }
      return cellValue;
    },
    /** 查询栏目列表 */
    getColumnList() {
      listConlumnList().then(response => {
        this.columnOptions = response.rows;
      });
    },
    /** 查询river_news列表 */
    getList() {
      this.loading = true;
      // 克隆queryParams以避免直接修改，并确保添加日期范围参数
      const params = {
        ...this.queryParams,
        beginPubdate: this.queryParams.beginPubdate,
        endPubdate: this.queryParams.endPubdate
      };
      listRiver_news(params).then(response => {
        //查找columnId对应的栏目名称
        this.river_newsList = response.rows.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            columnName: column ? column.name : '未知栏目'
          }
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        newsId: null,
        title: null,
        articleOrigin: null,
        columnId: null,
        content: null,
        author: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        coverPath: null,
        pubdate: null,
        littleTitle1: null, // 清空副标题1
        littleTitle2: null, // 清空副标题2
        status: '0', // 默认状态为显示
      };
      this.subtitles = []; // 清空副标题数组
      this.fileList = []; // 清空文件列表
      this.uploadFile = null; // 清空上传文件
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 添加日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginPubdate = this.dateRange[0];
        this.queryParams.endPubdate = this.dateRange[1];
      } else {
        this.queryParams.beginPubdate = undefined;
        this.queryParams.endPubdate = undefined;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.queryParams.beginPubdate = undefined;
      this.queryParams.endPubdate = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.originalFilePath = "";
      this.open = true;
      this.title = "添加河道要闻";
      // 清空文件上传相关的引用
      this.$nextTick(() => {
        const uploadComponent = this.$refs.upload;
        if (uploadComponent) {
          uploadComponent.clearFiles();
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const newsId = row.newsId || this.ids
      getRiver_news(newsId).then(response => {
        this.form = response.data;
        this.originalFilePath = this.form.coverPath || '';
        this.open = true;
        this.title = "修改精选";
        // 初始化文件列表
        if (this.form.coverPath) {
          this.fileList = [{
            name: '封面图片',
            url: this.form.coverPath
          }];
        } else {
          this.fileList = [];
          this.uploadFile = null;
        }
        //console.log('修改时初始化表单数据：', this.form);
        // 同步副标题状态 - 修改部分1：初始化时检查已有的副标题
        this.subtitles = [];
        // 检查是否存在副标题1，如果存在则添加到显示列表
        if (this.form.littleTitle1 || this.form.little_title1) {
          this.subtitles.push('littleTitle1');
        }
        // 检查是否存在副标题2，如果存在则添加到显示列表
        if (this.form.littleTitle2 || this.form.little_title2) {
          this.subtitles.push('littleTitle2');
        }
        // 如果没有任何副标题但允许添加，则默认显示一个空的副标题输入框
        if (this.subtitles.length === 0) {
          this.subtitles.push('littleTitle1');
        }
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        try {
          // 处理封面上传
          if (this.uploadFile) {
            await this.uploadFileToServer(this.uploadFile);
          }

          // 提交表单数据
          if (this.form.newsId != null) {
            await updateRiver_newsOwn(this.form);
            this.$modal.msgSuccess("修改成功");
          } else {
            // 移除了8条限制，现在可以持续添加，系统会自动管理只显示最新的8条
            await addRiver_newsOwn(this.form);
            this.$modal.msgSuccess("新增成功");
          }
          this.open = false;
          this.getList();
        } catch (error) {
          console.error('操作失败:', error);
          this.$message.error(`操作失败: ${error.message}`);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认删除river_news编号为"' + newsIds + '"的数据项？').then(function() {
        return delRiver_news(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 切换河道要闻状态 */
    handleToggleStatus(row) {
      const newsId = row.newsId;
      const status = row.status;

      if (status === 0 || status === '0') {
        // 当前是显示状态，切换为隐藏
        this.$modal.confirm('是否确认隐藏该河道要闻？').then(() => {
          return hideRiverNews(newsId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("隐藏成功");
        }).catch(() => {});
      } else {
        // 当前是隐藏状态，切换为显示
        this.$modal.confirm('是否确认显示该河道要闻？').then(() => {
          return showRiverNews(newsId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("显示成功");
        }).catch(() => {});
      }
    },
    // 文件上传前处理
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt1M = file.size / 1024 / 1024 < 1; // 检查是否小于1MB

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (isLt1M) {
        this.$message.error('图片大小不能小于1MB!');
        return false;
      }

      this.uploadFile = file;
      return false; // 阻止自动上传
    },

    // 文件变化处理
    handleFileChange(file, fileList) {
      console.log('封面文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadFile = fileList[0].raw;
        this.fileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('更新 uploadFile:', this.uploadFile);
      } else {
        this.uploadFile = null;
        this.fileList = [];
        console.log('清空 uploadFile');
      }
    },

    // 文件移除处理
    handleRemove() {
      console.log('封面文件移除处理');
      this.uploadFile = null;
      this.form.coverPath = null;
      this.fileList = [];
      console.log('清空 uploadFile 和 coverPath');
    },

    // 上传请求处理
    handleHttpRequest(options) {
      console.log('封面上传请求处理:', options);
      this.uploadFileToServer(options.file);
    },

    // 使用 Canvas 进行图片压缩，可以更精确地控制文件大小
    async compressImage(file) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      // 检查文件是否小于最小大小
      if (file.size < minSizeBytes) {
        throw new Error('图片大小不能小于1MB!');
      }

      // 如果文件小于 3MB，直接跳过压缩
      if (file.size < skipCompressSizeBytes) {
        console.log(`文件大小为 ${file.size} bytes，小于 3MB，跳过压缩`);
        return file;
      }

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // 使用 Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 上传文件到服务器
    async uploadFileToServer(file) {
      try {
        // 压缩图片
        console.log('提交前压缩封面图片');
        const compressedFile = await this.compressImage(file);

        const formData = new FormData();
        formData.append('file', compressedFile);

        console.log('调用封面上传API，ID:', this.form.newsId || 0);
        const response = await uploadFile(this.form.newsId || 0, formData);

        console.log('封面上传响应:', response);
        if (response.code === 200) {
          this.form.coverPath = response.url;
          this.$message.success('封面图片上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('封面图片上传失败: ' + error.message);
        throw error;
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('river_news/river_news/export', {
        ...this.queryParams
      }, `river_news_${new Date().getTime()}.xlsx`)
    },

    /** 上移河道要闻 */
    moveUp(row) {
      this.$modal.confirm('是否确认上移该河道要闻？').then(() => {
        return moveUpRiverNews(row.newsId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("上移成功");
      }).catch(() => {});
    },

    /** 下移河道要闻 */
    moveDown(row) {
      this.$modal.confirm('是否确认下移该河道要闻？').then(() => {
        return moveDownRiverNews(row.newsId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("下移成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.subtitle-item {
  margin-bottom: 20px;
}
</style>
